{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 成语接龙\n",
    "- 简单版：不考虑声调\n",
    "- 困难版：考虑声调"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "构建完成\n"
     ]
    }
   ],
   "source": [
    "d = {}\n",
    "# c2p = {}\n",
    "with open('data/IdiomPY.txt', 'r', encoding='gbk') as f:\n",
    "    for l in f:\n",
    "        ret = l.split('[')\n",
    "        idiom = ret[0]\n",
    "        pinyin = ret[1].replace(']\\n', '').split(' ')\n",
    "        \n",
    "        if d.get(pinyin[0]):\n",
    "            d[pinyin[0]].append([idiom, pinyin[-1]])\n",
    "        else:\n",
    "            d[pinyin[0]] = [[idiom, pinyin[-1]]]\n",
    "            \n",
    "# #         c2p[idiom[-1]] = pinyin[-1]\n",
    "print('构建完成')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "镜花水月\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "\n",
    "def q(py=''):\n",
    "    if py == '':\n",
    "        i = random.randint(0, len(d.keys())-1)\n",
    "        c = 0\n",
    "        for pinyin in d.keys():\n",
    "            if c == i:\n",
    "                ret = d[pinyin]\n",
    "                index = random.randint(0, len(ret)-1)\n",
    "#                 print(d[ret[index][1]])\n",
    "                return ret[index]\n",
    "            c += 1\n",
    "    else:\n",
    "#         print(d[d[py][0][1]])\n",
    "        return d[py][0]\n",
    "        \n",
    "def play(qna):\n",
    "    print(qna[0])\n",
    "    userA = input()\n",
    "    for pair in d[qna[1]]:\n",
    "        if userA == pair[0]:\n",
    "            play(q(pair[1]))\n",
    "            break\n",
    "    print('你的回答有问题')\n",
    "    \n",
    "play(q())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
